﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using yq.IService;
using System.ServiceModel.Activation;
using System.ServiceModel;
using yq.Dictionary;
using System.IO;
using Db;

namespace yq.Service
{
    /// <summary>
    /// 上传下载文件
    /// </summary>
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
    public class Upload : IUpload
    {
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public yq.Dictionary.ReturnValue<string> UpFile(byte[] fliebyte, yq.Model.Logic.SysFile file)
        {
            return NewFile(fliebyte, file);
        }

        /// <summary>
        /// 上传文本
        /// </summary>
        /// <param name="txt"></param>
        /// <param name="modelId"></param>
        /// <returns></returns>
        public yq.Dictionary.ReturnValue<string> UpTxt(string txt, string modelId)
        {
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(txt);
            yq.Model.Logic.SysFile file = new Model.Logic.SysFile()
            {
                DownCount = 0,
                Extension = "txt",
                FileSize = byteArray.Length,
                FlieName = "",
                IsDel = Enums.BooleanType.No,
                ModelId = modelId
            };
            return NewFile(byteArray, file);
        }

        /// <summary>
        /// 编辑文本
        /// </summary>
        /// <param name="id"></param>
        /// <param name="txt"></param>
        /// <returns></returns>
        public yq.Dictionary.ReturnValue<string> EditTxt(string id, string txt)
        {
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(txt);

            return UpdateFile(byteArray, yq.Model.Logic.SysFile.Load(id));
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DeleteFile(string id)
        {
            //保存到数据库和文件
            Func<DbHelper, yq.CaCheRefresh, bool> dbfun = (cn, ca) =>
            {
                var model = yq.Model.Logic.SysFile.Load(id);

                if (model.IsLoad)
                {
                    new yq.Business.SysFileDal().Update(model, cn);
                    cn.Commit();
                    return true;
                }
                return false;
            };

            return Db.DBTrans.DoTrans(dbfun);
        }


        /// <summary>
        /// 获取文本
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string DownFileTxt(string id)
        {
            string txt = "";
            var info = yq.Model.Logic.SysFile.Load(id);

            if (info.IsLoad)
            {
                using (System.IO.StreamReader sm = new StreamReader(info.SavePath))
                {
                    txt = sm.ReadToEnd().ExtFilterScript();
                }
            }

            return txt;
        }

        /// <summary>
        /// 下载图片
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public byte[] DownFileImg(string id, int maxWidth, int maxHeight, int quality)
        {
            const string tp = "{2}_w{0}__h{1}_e";
            byte[] bt = new byte[1];
            var info = yq.Model.Logic.SysFile.Load(id);

            if (info.IsLoad)
            {
                string savePath = string.Format(tp, maxWidth.ToString(), maxHeight.ToString(), info.SavePath);
                
                //检查是否有缩略图
                if (System.IO.File.Exists(savePath) == false)
                {
                    //读取原图
                    using (System.IO.FileStream sm = new FileStream(info.SavePath, FileMode.Open, FileAccess.Read))
                    {
                        //判断是不是图片
                        if (IsPicture(sm) == false)
                        {
                            return bt;
                        }
                        cn.Util.ImageTools.CutForCustom(sm, savePath, maxWidth, maxHeight, quality);
                    }
                }

                //读取剪切的图片
                using (System.IO.FileStream sm = new FileStream(savePath, FileMode.Open, FileAccess.Read))
                {
                    bt = new byte[sm.Length];
                    sm.Read(bt, 0, bt.Length);
                }
            }

            return bt;
        }

        /// <summary>
        /// 根据文件头判断上传的文件类型
        /// </summary>
        /// <param name="filePath">filePath是文件的完整路径 </param>
        /// <returns>返回true或false</returns>
        private bool IsPicture(FileStream fs)
        {
            try
            {
                BinaryReader reader = new BinaryReader(fs);
                    string fileClass;
                    byte buffer;
                    buffer = reader.ReadByte();
                    fileClass = buffer.ToString();
                    buffer = reader.ReadByte();
                    fileClass += buffer.ToString();

                    //255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar 
                    if (fileClass == "255216" || fileClass == "7173" || fileClass == "13780" || fileClass == "6677")
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
            }
            catch
            {
                return false;
            }
        }


        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public byte[] DownFile(string id)
        {
            byte[] bt = new byte[1];
            var info = yq.Model.Logic.SysFile.Load(id);

            if (info.IsLoad)
            {
                using (System.IO.FileStream sm = new FileStream(info.SavePath, FileMode.OpenOrCreate, FileAccess.Read))
                {
                    bt = new byte[sm.Length];
                    sm.Read(bt, 0, bt.Length);
                }
            }

            return bt;
        }


        /// <summary>
        /// 创建文件 内部
        /// </summary>
        /// <param name="fliebyte"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        private ReturnValue<string> NewFile(byte[] fliebyte, yq.Model.Logic.SysFile file)
        {
            ReturnValue<string> rv = new ReturnValue<string>();
            file.FlieId = "guid".ExtNewGuid();
            file.SubmitTime = DateTime.Now;
            file.IsDel = Enums.BooleanType.No;
            file.SavePath = cn.Util.WebConfig.SaveFliePath;

            if (file.SavePath == null || file.SavePath.Length == 0)
            {
                rv.False("未定义SaveFliePath");
                return rv;
            }

            file.SavePath = file.SavePath + file.SubmitTime.ToString("yyyyMMdd") + @"\" + file.FlieId.Substring(0, 2) + @"\";

            //创建文件
            Directory.CreateDirectory(file.SavePath);

            file.SavePath += file.FlieId;

            //保存到数据库和文件
            Action<DbHelper, yq.CaCheRefresh> dbfun = (cnheper, ca) =>
            {
                using (FileStream sw = new FileStream(file.SavePath, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    Encoder ec = Encoding.UTF8.GetEncoder();

                    byte[] byDataValue = new byte[fliebyte.Length];
                    sw.Write(fliebyte, 0, fliebyte.Length);
                }

                new yq.Business.SysFileDal().Add(file, file.FlieId, cnheper);
                cnheper.Commit();
            };

            Db.DBTrans.DoTrans(dbfun);

            rv.True(file.FlieId);

            return rv;
        }

        /// <summary>
        /// 修改文件 内部
        /// </summary>
        /// <param name="fliebyte"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        private ReturnValue<string> UpdateFile(byte[] fliebyte, yq.Model.Logic.SysFile file)
        {
            ReturnValue<string> rv = new ReturnValue<string>();

            //保存到数据库和文件
            Action<DbHelper, yq.CaCheRefresh> dbfun = (cn, ca) =>
            {
                using (FileStream sw = new FileStream(file.SavePath, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    Encoder ec = Encoding.UTF8.GetEncoder();

                    byte[] byDataValue = new byte[fliebyte.Length];
                    sw.Write(fliebyte, 0, fliebyte.Length);
                }

                new yq.Business.SysFileDal().Update(file, cn);
                cn.Commit();
            };

            Db.DBTrans.DoTrans(dbfun);
            rv.True(file.FlieId);

            return rv;
        }

    }
}
